package org.mspring.mlog.service.impl;

import java.util.Date;
import java.util.List;

import org.mspring.mlog.entity.PostCatalog;
import org.mspring.mlog.service.PostCatalogService;
import org.mspring.platform.dao.hibernate.GenericDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 
 * @author Gao Youbo
 * @since 2013-06-18 16:34:42
 */
@Service
@Transactional
public class PostCatalogServiceImpl extends GenericDao<PostCatalog, java.lang.Long> implements PostCatalogService {

    @Override
    public PostCatalog save(PostCatalog object) {
        // TODO Auto-generated method stub
        object.setCreateTime(new Date());
        return super.save(object);
    }

    @Override
    public void update(PostCatalog object) {
        // TODO Auto-generated method stub
        object.setModifyTime(new Date());
        super.update(object);
    }

    @Override
    public PostCatalog getPostCatalogByName(String name) {
        // TODO Auto-generated method stub
        return uniqueResult("select catalog from PostCatalog catalog where catalog.name = ?", name);
    }

    @Override
    public boolean postCatalogExists(String name, Long id, Long user) {
        // TODO Auto-generated method stub
        int count = 0;
        if (id == null) {
            count = getHibernateTemplate().count("select count(*) from PostCatalog catalog where catalog.name = ? and catalog.user.id = ?", name, user);
        } else {
            count = getHibernateTemplate().count("select count(*) from PostCatalog catalog where catalog.name = ? and catalog.user.id = ? and catalog.id <> ?", name, user, id);
        }
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void setPostCatalogOrders(Long[] ids, Long[] orders) {
        // TODO Auto-generated method stub
        if (ids == null || orders == null || ids.length == 0 || orders.length == 0) {
            return;
        }
        if (ids.length != orders.length) {
            return;
        }
        for (int i = 0; i < ids.length; i++) {
            Long id = ids[i];
            Long order = orders[i];
            if (id == null) {
                continue;
            }
            executeUpdate("update PostCatalog c set c.order = ? where c.id = ?", order, id);
        }
    }

    @Override
    public List<PostCatalog> findPostCatalogByUser(Long user) {
        // TODO Auto-generated method stub
        return list("select postCatalog from PostCatalog postCatalog where postCatalog.user.id = ?", user);
    }

    @Override
    public void safeRemove(Long id, Long user) {
        // TODO Auto-generated method stub
        executeUpdate("delete from PostCatalog pc where pc.id = ? and pc.user.id = ?", id, user);
    }
}
